package com.food.restaurantpro.adapters;

import java.util.ArrayList;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.imageloader.FileCache;
import com.food.restaurantpro.objects.Promotion;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PromotionListViewAdapter extends ArrayAdapter<Promotion> {
	private LayoutInflater inflater;
	private Context mContext;
	ArrayList<Promotion> mPromotionList;
	private FileCache m_FileCache;

	//
	private static class PromotionHolder {
		public TextView tvTitle;
		public TextView tvContent;
		public ImageView imgv;
	}

	public PromotionListViewAdapter(Context context,
			ArrayList<Promotion> promotionList) {
		super(context, R.layout.lv_item_promotion,
				R.id.tv_title_promotion_item, promotionList);
		this.mContext = context;
		inflater = LayoutInflater.from(mContext);
		mPromotionList = promotionList;
		m_FileCache = new FileCache(RestaurantApp.CURRENT_CONTEXT);
	}

	@Override
	public int getCount() {
		return mPromotionList.size();
	}

	@Override
	public Promotion getItem(int position) {
		return mPromotionList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View listView = convertView;
		PromotionHolder holder = null;
		if (convertView == null) {
			holder = new PromotionHolder();
			listView = inflater.inflate(R.layout.lv_item_promotion, null);
			holder.tvTitle = (TextView) listView
					.findViewById(R.id.tv_title_promotion_item);
			holder.tvContent = (TextView) listView
					.findViewById(R.id.tv_content_promotion_item);
			holder.imgv = (ImageView) listView
					.findViewById(R.id.imgv_promotion_item);
			listView.setTag(holder);

		} else {
			listView = convertView;
			holder = (PromotionHolder) listView.getTag();
		}
		Promotion promotion = mPromotionList.get(position);
		holder.tvTitle.setText(promotion.getPromotionName());
		holder.tvContent.setText(promotion.getPromotionDescription());
		holder.imgv.setImageBitmap(m_FileCache.getBitmapByUrl(promotion
				.getPromotionImageThumbnail()));
		holder.imgv.setScaleType(ImageView.ScaleType.FIT_XY);

		return listView;
	}

	public void clearMemoryCache() {
		if (mPromotionList != null) {
			mPromotionList.clear();
			mPromotionList = null;
		}
		inflater = null;
	}
}
